package com.wnzt.baszh.util.common;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.Service;
import javax.xml.rpc.encoding.XMLType;

import org.apache.axis.client.Call;
import org.apache.log4j.Logger;
import org.apache.xml.security.exceptions.Base64DecodingException;
import org.apache.xml.security.utils.Base64;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.tree.BaseElement;

import com.wnzt.baszh.entity.MedicalFile;
import com.wnzt.baszh.entity.MedicalPdf;

/**
 * webservice工具类
 * @author [lv tang wei]
 * [2017年5月19日]
 */
public class WebServiceUtil {
    
    Map<String, String> maptparam = new HashMap<String, String>();
    
    private Call call = null;
    
    
    Logger log = Logger.getLogger(WebServiceUtil.class);
    
    /**
     * @author [lv tang wei]
     * Describe:解析调用个人电子全部病历结果
     * @param strxml
     * @return
     * [2017年5月19日]
     * @throws Exception 
     */
	public List<MedicalFile> parserMedicalFilelistResultXml(String strxml) throws Exception {
		List<MedicalFile> list = new ArrayList<MedicalFile>();
		Document document = DocumentHelper.parseText(strxml);
		if (document == null)
			return null;
		Element rootElement = document.getRootElement();
		/*100	成功
		101	入参格式错误
		102	其他错误*/
		String result = rootElement.element("result").getTextTrim();
		String resultinfo = rootElement.element("resultinfo").getText();
		if("100".equals(result)){
			List<Node> nodeList=rootElement.selectNodes("medicalfile");
			for (Node node : nodeList) {
				MedicalFile mf=new MedicalFile();
				mf.setMedicalid(node.selectSingleNode("medicalid").getText());
				mf.setFtype(Integer.parseInt(node.selectSingleNode("ftype").getText()));
				mf.setFtitle(node.selectSingleNode("ftitle").getText());
				mf.setFpdfpath(node.selectSingleNode("fpdfpath").getText());
				list.add(mf);
			}
		}
		return list;
	}
	
	/**
     * @author [lv tang wei]
     * Describe:解析调用个人电子病历pdf
     * @param strxml
     * @return
     * [2017年5月19日]
	 * @throws Base64DecodingException 
	 * @throws DocumentException 
     */
	public List<MedicalPdf> parserMedicalPdfResultXml(String strxml) throws Base64DecodingException, DocumentException {
		List<MedicalPdf> list = new ArrayList<MedicalPdf>();
		Document document = DocumentHelper.parseText(strxml);
		if (document == null)
			return null;
		Element rootElement = document.getRootElement();
		/*100	成功
		101	入参格式错误
		102	其他错误*/
		String result = rootElement.element("result").getTextTrim();
		String resultinfo = rootElement.element("resultinfo").getText();
		if("100".equals(result)){
			List<Node> nodeList=rootElement.selectNodes("medicalpdf");
			for (Node node : nodeList) {
				MedicalPdf mp=new MedicalPdf();
				mp.setMedicalid(node.selectSingleNode("medicalid").getText());
				byte[] bytes = Base64.decode(node.selectSingleNode("filebyte").getText());
				mp.setFilebyte(bytes);
				mp.setFpath(node.selectSingleNode("fpath").getText());
				list.add(mp);
			}
		}
		return list;
	}
	
	public static void printNode(List<Node> nodeList) {
        for (Node jobNode : nodeList) {
            printProperty(jobNode.selectObject("medicalid"));
           
        }
    }
    public static String printProperty(Object node) {
    	return ((Node)node).getText();
    }
	/**
	 * 
	 * @author [lv tang wei]
	 * Describe:
	 * @param strxml
	 * @return
	 * [2017年5月22日]
	 * @throws Exception 
	 */
	public MedicalFile parserUploadPdfXml(String strxml) throws Exception {
		MedicalFile mf=new MedicalFile();
		List<MedicalPdf> list = new ArrayList<MedicalPdf>();
		try {
			Document document = DocumentHelper.parseText(strxml);
			if (document == null)
				return null;
			
			Element rootElement = document.getRootElement();
			String fzyid = rootElement.element("fzyid").getTextTrim();
			String fprn = rootElement.element("fprn").getTextTrim();
			String ftimes = rootElement.element("ftimes").getTextTrim();
			String fname = rootElement.element("fname").getTextTrim();
			if(!GlobalFun.hasValue(fzyid)||!GlobalFun.hasValue(fprn)||!GlobalFun.hasValue(ftimes)||!GlobalFun.hasValue(fname)){
				throw new Exception("入参参数必填项信息不全.");
			}

			List<Node> nodeList=rootElement.selectNodes("medicalpdf");
			for (Node node : nodeList) {
				MedicalPdf mp=new MedicalPdf();
				mp.setMedicalid(node.selectSingleNode("medicalid").getText());
				mp.setFtype(node.selectSingleNode("ftype").getText());
				mp.setFtitle(node.selectSingleNode("ftitle").getText());
				byte[] bytes = Base64.decode(node.selectSingleNode("filebyte").getText());
				mp.setFilebyte(bytes);
				mp.setFpath(node.selectSingleNode("fpath").getText());
				list.add(mp);
			}
			
			mf.setFzyid(fzyid);
			mf.setFprn(fprn);
			mf.setFtimes(ftimes);
			mf.setFname(fname);
			mf.setMedicalPdfs(list);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			throw new Exception(e.getMessage());
			
		}
		return mf;
	}
	
	/**
	 * 
	 * @author [lv tang wei]
	 * Describe:
	 * @param strxml
	 * @return
	 * [2017年5月22日]
	 * @throws Exception 
	 */
	public MedicalFile parserUploadPDFXml(String strxml) throws Exception {
		MedicalFile mf=new MedicalFile();
		try {
			Document document = DocumentHelper.parseText(strxml);
			if (document == null)
				return null;
			
			Element rootElement = document.getRootElement();
			//String fprn = rootElement.element("fprn").getTextTrim();//病案号
			//String ftimes = rootElement.element("ftimes").getTextTrim();//住院次数
			//String fzyid = rootElement.element("fzyid").getTextTrim();//住院次数
			String ftitle = rootElement.element("ftitle").getTextTrim();//文件名
			String ffilehash=rootElement.element("ffilehash").getTextTrim();//源文件hash值(哈希算法MD5)
			String filebyte=rootElement.element("filebyte").getText();
			String ffilehashsign=rootElement.element("ffilehashsign").getTextTrim();//源文件hash码ca签名值(哈希算法MD5)
			if(!GlobalFun.hasValue(ffilehash)){
				throw new Exception("原文HASH码为空.");
			}
			if(!GlobalFun.hasValue(ffilehashsign)){
				throw new Exception("原文HASH码签名为空.");
			}
			if(!GlobalFun.hasValue(filebyte)){
				throw new Exception("原文数据流为空.");
			}
			byte[] bytes = Base64.decode(filebyte);//源文件流
			mf.setFilebyte(bytes);
			mf.setFfilehash(ffilehash);
			mf.setFfilehashsign(ffilehashsign);
			mf.setFtitle(ftitle);
			//mf.setFprn(fprn);
			//mf.setFtimes(ftimes);
			//mf.setFtitle(ftitle);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage()+"解析异常:"+strxml);
			throw new Exception(e.getMessage());
		}
		return mf;
	}
	
	/**
	 * @author [lv tang wei]
	 * Describe:集中浏览归档解析
	 * @param strxml
	 * @return
	 * @throws Exception
	 * [2017年5月25日]
	 */
	public MedicalFile parserBrowseArchiveXml(String strxml) throws Exception {
		MedicalFile mf=new MedicalFile();
		Document document = DocumentHelper.parseText(strxml);
		if (document == null)
			return null;
		
		Element rootElement = document.getRootElement();
		String fzyid = rootElement.element("fzyid").getTextTrim();
		String fprn = rootElement.element("fprn").getTextTrim();
		String ftimes = rootElement.element("ftimes").getTextTrim();
		String fname = rootElement.element("fname").getTextTrim();
		if(!GlobalFun.hasValue(fzyid)||!GlobalFun.hasValue(fprn)||!GlobalFun.hasValue(ftimes)||!GlobalFun.hasValue(fname)){
			throw new Exception("入参参数必填项信息不全.");
		}
		mf.setFzyid(fzyid);
		mf.setFprn(fprn);
		mf.setFtimes(ftimes);
		mf.setFname(fname);
		return mf;
	}
	
	
	/**
	 * 入参转xml
	 * @author [lv tang wei]
	 * Describe:
	 * @param fsfzh
	 * @return
	 * [2017年5月19日]
	 */
	public String getMedicalFilelistParamStr(Map<String,Object> data) {
		Document doc = DocumentHelper.createDocument();
		doc.setXMLEncoding("UTF-8");
		Element el = doc.addElement("data");

		Element fzyid = new BaseElement("fzyid");
		fzyid.setText(data.get("FZYID")+"");
		el.add(fzyid);

		Element fprn = new BaseElement("fprn");
		fprn.setText(data.get("FPRN")+"");
		el.add(fprn);
		
		Element ftimes = new BaseElement("ftimes");
		ftimes.setText(data.get("FTIMES")+"");
		el.add(ftimes);
		
		Element fname = new BaseElement("fname");
		fname.setText(data.get("FNAME")+"");
		el.add(fname);

		String parXML = doc.asXML();
		return parXML;
	}
	
	/**
	 * 入参转xml
	 * @author [lv tang wei]
	 * Describe:
	 * @param fsfzh
	 * @return
	 * [2017年5月19日]
	 */
	public String getMedicalPdfParamStr(Map<String,Object> data) {
		Document doc = DocumentHelper.createDocument();
		doc.setXMLEncoding("UTF-8");
		Element el = doc.addElement("data");

		Element fzyid = new BaseElement("fzyid");
		fzyid.setText(data.get("FZYID")+"");
		el.add(fzyid);

		Element fprn = new BaseElement("fprn");
		fprn.setText(data.get("FPRN")+"");
		el.add(fprn);
		
		Element ftimes = new BaseElement("ftimes");
		ftimes.setText(data.get("FTIMES")+"");
		el.add(ftimes);
		
		Element fname = new BaseElement("fname");
		fname.setText(data.get("FNAME")+"");
		el.add(fname);
		
		Element medicalids = new BaseElement("medicalids");
		medicalids.setText(data.get("MEDICALIDS")+"");
		el.add(medicalids);

		String parXML = doc.asXML();
		return parXML;
	}
	
	public String getMedicalPdfParamStr(MedicalFile mf) {
		Document doc = DocumentHelper.createDocument();
		doc.setXMLEncoding("UTF-8");
		Element el = doc.addElement("data");

		Element fzyid = new BaseElement("fzyid");
		fzyid.setText(mf.getFzyid());
		el.add(fzyid);

		Element fprn = new BaseElement("fprn");
		fprn.setText(mf.getFprn());
		el.add(fprn);
		
		Element ftimes = new BaseElement("ftimes");
		ftimes.setText(mf.getFtimes());
		el.add(ftimes);
		
		Element fname = new BaseElement("fname");
		fname.setText(mf.getFname());
		el.add(fname);
		
		Element medicalids = new BaseElement("medicalids");
		medicalids.setText(mf.getMedicalid());
		el.add(medicalids);

		String parXML = doc.asXML();
		return parXML;
	}
	/**
	 * 根据读取配置连接webservice
	 * @author [lv tang wei]
	 * Describe:
	 * @return
	 * @throws Exception
	 * [2017年5月19日]
	 */
	public Call getMedicalCall() throws Exception{
		String rcp_path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		FileInputStream file = null;
		Properties properties = new Properties();
		file = new FileInputStream(new File(rcp_path
				+ "config.properties"));
		properties.load(file);
		Service service = new org.apache.axis.client.Service();
		call = (Call) service.createCall();
		call.setTargetEndpointAddress(properties.getProperty("auto.medical.webUrl"));
		call.setOperationName(new QName(properties.getProperty("auto.medical.OperationName"), properties.getProperty("auto.medical.execute")));// WSDL里面描述的接口名称
		call.addParameter(properties.getProperty("auto.medical.Parameter"), XMLType.XSD_STRING, ParameterMode.IN);//
		call.setReturnType(XMLType.XSD_STRING);// 设置返回类型
		call.setProperty(Call.CONNECTION_TIMEOUT_PROPERTY, new Integer(50000));//连接超时设置
		call.setTimeout(new Integer(50000));//超时设置
		return call;
	}
	
	/**
	 * 根据读取配置连接webservice 
	 * @author [lv tang wei]
	 * Describe:
	 * @return
	 * @throws Exception
	 * [2017年5月19日]
	 */
	public Call getMedicalPdfCall() throws Exception{
		String rcp_path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		FileInputStream file = null;
		Properties properties = new Properties();
		file = new FileInputStream(new File(rcp_path
				+ "config.properties"));
		properties.load(file);
		Service service = new org.apache.axis.client.Service();
		call = (Call) service.createCall();
		call.setTargetEndpointAddress(properties.getProperty("auto.pdf.webUrl"));
		call.setOperationName(new QName(properties.getProperty("auto.pdf.OperationName"), properties.getProperty("auto.pdf.execute")));// WSDL里面描述的接口名称
		call.addParameter(properties.getProperty("auto.pdf.Parameter"), XMLType.XSD_STRING, ParameterMode.IN);//
		call.setReturnType(XMLType.XSD_STRING);// 设置返回类型
		call.setProperty(Call.CONNECTION_TIMEOUT_PROPERTY, new Integer(50000));//连接超时设置
		call.setTimeout(new Integer(50000));//超时设置
		return call;
	}
	
	//创建文件夹--多层  
	public static boolean CreateMultilayerFile(String dir){  
	    try {  
	           File dirPath = new File(dir);  
	           if (!dirPath.exists()) {  
	               dirPath.mkdirs();  
	           }  
	       } catch (Exception e) {  
	          System.out.println("创建多层目录操作出错: "+e.getMessage());  
	           e.printStackTrace();  
	           return false;  
	       }  
	    return true;  
	} 
	
}
